/* CAMERA.C */

/*
	Copyright (C) 2010 by Lesnikov Andrey <ozkriff@gmail.com>
	This file is part of ozkriff_game_2.

	ozkriff_game_2 is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	ozkriff_game_2 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with ozkriff_game_2.  If not, see <http://www.gnu.org/licenses/>.

	See the COPYING file for more details.
*/

#include <math.h>

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
#include <stdbool.h>

#include "defines.h"
#include "nograph.h"
#include "camera.h"

extern int cursorX, cursorY;
extern int SCR_HEIGHT, SCR_WIDTH;
extern float HEX_EX, HEX_IN;


camera CAMERA = {0, 0, 0, 45, 8, false};
bool CANCAMROT = false; //задвинуть в структуру!


void
set_camera()
{
	glLoadIdentity();
	glTranslatef(0, 0, -CAMERA.distanse); //отдаление
	glRotatef(-CAMERA.vert_angle, 1, 0, 0);
	glRotatef(CAMERA.horiz_angle, 0, 0, 1);
	glTranslatef(CAMERA.x, CAMERA.y, 0);
}



void
camera_logic()
{
	if(CAMERA.is_rotating || !CANCAMROT)
		return;

	float lastx = CAMERA.x; //запомним последние координаты.
	float lasty = CAMERA.y; //если выходим за границы карты - откатимся на них.
	
	// насколько близко к краям экрана надо придвинуть
	// мышу, что бы началось перемещение
	int border = 30;
	
	if (cursorY < border) { // наверху. двигаемся вперед
		CAMERA.x -= sinf(CAMERA.horiz_angle*M_PI/180.0f)*0.1;
		CAMERA.y -= cosf(CAMERA.horiz_angle*M_PI/180.0f)*0.1;
	}
	if (cursorY > SCR_HEIGHT - border) { //курсор снизу. двигаемся назад.
		CAMERA.x += sinf(CAMERA.horiz_angle*M_PI/180.0f)*0.1;
		CAMERA.y += cosf(CAMERA.horiz_angle*M_PI/180.0f)*0.1;
	}
	
	if (cursorX < border) { //лево.
		CAMERA.x += sinf((CAMERA.horiz_angle+90.0)*M_PI/180.0)*0.1;
		CAMERA.y += cosf((CAMERA.horiz_angle+90.0)*M_PI/180.0)*0.1;
	}
	if (cursorX > SCR_WIDTH - border) { //право.
		CAMERA.x -= sinf((CAMERA.horiz_angle+90.0)*M_PI/180.0)*0.1;
		CAMERA.y -= cosf((CAMERA.horiz_angle+90.0)*M_PI/180.0)*0.1;
	}
	
	//проверка границ + откаты на предыдущие позиции
	if (CAMERA.x > 0) CAMERA.x = lastx;
	if (CAMERA.y > 0) CAMERA.y = lasty;
	if (CAMERA.x < -2*HEX_IN*(MAP_SIZE_X-1)) CAMERA.x = lastx;
	if (CAMERA.y < -1.5*HEX_EX*(MAP_SIZE_Y-1)) CAMERA.y = lasty;
}


void
init_camera()
{
	map_to_real(MAP_SIZE_X/2, MAP_SIZE_Y/2, &(CAMERA.x), &(CAMERA.y));
	CAMERA.x = -CAMERA.x;
	CAMERA.y = -CAMERA.y;
}
